package com.lujianfei.powersearch.ui.select.viewmodel

import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.utils.Constant
import com.lujianfei.powersearch.utils.DatabindingDiffUtils
import com.orm.SugarRecord
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SelectNodeViewModel: ViewModel() {

    val data = ObservableArrayList<SearchItemModel>()

    var selectId:Long = -1

    var onItemClickCallback: ((SearchItemModel) -> Unit)?= null
    val onItemClick: ((SearchItemModel) -> Unit) = {
        onItemClickCallback?.invoke(it)
    }
    var onItemLongClickCallback: ((SearchItemModel) -> Unit)?= null
    val onItemLongClick: ((SearchItemModel) -> Unit) = {
        onItemLongClickCallback?.invoke(it)
    }

    val loading = ObservableBoolean(false)
    fun loadData(searchItemModel: SearchItemModel?) {
        loading.set(true)
        viewModelScope.launch {
            val resp = withContext(Dispatchers.IO) {
                val searchItemModels = SugarRecord.find(SearchItemModel::class.java, "parentId=? order by name", "${searchItemModel?.id?: Constant.RootId}")
                searchItemModels.sortByDescending { it.sort }
                searchItemModels.forEach {
                    it.selectId = selectId
                    updateCost(it)
                }
                searchItemModels
            }
            loading.set(false)
            DatabindingDiffUtils.setData(oldList = data, newList = resp)
        }
    }

    fun updateCost(item:SearchItemModel) {
        val childList = SugarRecord.find(SearchItemModel::class.java, "parentId=?", "" + item.id)
        if (childList == null || childList.isEmpty()) {
            return
        } else {
            runCatching {
                val childSum = childList.sumOf { if (it.cost.isNullOrBlank()) 0.0 else it.cost!!.toDouble() }
                if (childSum > 0.0) {
                    item.cost = childSum.toString()
                    item.save()
                }
            }
            childList.forEach {
                updateCost(it)
            }
        }
    }
}